const app = getApp();

Page({
  data: {
    users: [],          // 原始用户数据
    formatUsers: [],    // 格式化后用户数据
    currentPage: 1,     // 当前页码
    pageSize: 10,       // 每页条数
    total: 0,           // 总用户数
    totalPages: 0,      // 总页数
    searchKey: '',      // 搜索关键词
    isLoading: false,   // 加载状态
    showUserModal: false,// 用户弹窗
    isEditMode: false,  // 编辑模式标记
    roles: [],          // 角色列表（/api/roles/list返回）
    selectedRoleIndex: 0, // 选中的角色索引（修复关键）
    formData: {         // 弹窗表单数据
      id: '',
      username: '',
      phone: '',
      avatarUrl: '',
      role: '',         // 角色编码
      password: ''
    }
  },

  /**
   * 页面加载：先加载角色列表，再加载用户
   */
  onLoad() {
    this.checkLoginStatus();
    this.loadRolesList().then(() => {
      this.loadUsers();
    });
  },

  /**
   * 加载角色列表（/api/roles/list接口）
   */
  loadRolesList() {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token');
      wx.request({
        url: app.globalData.baseUrl + '/api/roles/list',
        method: 'GET',
        header: { 'Authorization': `Bearer ${token}` },
        success: (res) => {
          if (res.data.code === 200 && Array.isArray(res.data.data)) {
            const roles = res.data.data;
            // 初始化选中角色索引为0
            this.setData({ 
              roles,
              selectedRoleIndex: 0 
            });
            // 设置默认角色编码
            if (roles.length > 0) {
              this.setData({ 'formData.role': roles[0].roleCode });
            }
            resolve();
          } else {
            wx.showToast({ title: '加载角色失败', icon: 'none' });
            reject();
          }
        },
        fail: () => {
          wx.showToast({ title: '网络错误，角色加载失败', icon: 'none' });
          reject();
        }
      });
    });
  },

  /**
   * 加载用户列表
   */
  loadUsers() {
    this.setData({ isLoading: true });
    const token = wx.getStorageSync('token');
    const { currentPage, pageSize, searchKey } = this.data;

    wx.request({
      url: app.globalData.baseUrl + '/api/users',
      method: 'GET',
      header: { 'Authorization': `Bearer ${token}` },
      data: { 
        current: currentPage,
        size: pageSize,
        keyword: searchKey
      },
      success: (res) => {
        this.setData({ isLoading: false });
        if (res.data.code === 200 && Array.isArray(res.data.data)) {
          const rawUsers = res.data.data;
          const formatUsers = rawUsers.map(user => ({
            ...user,
            roleName: this.getRoleNameByCode(user.role),
            lastLoginTime: user.lastLoginTime ? this.formatTime(user.lastLoginTime) : '未登录',
            createTime: user.createTime ? this.formatTime(user.createTime) : '未知',
            password: '********'
          }));

          this.setData({
            users: rawUsers,
            formatUsers,
            total: res.data.total,
            currentPage: res.data.current,
            totalPages: Math.ceil(res.data.total / res.data.size)
          });
        } else {
          wx.showToast({ title: res.data.msg || '加载用户失败', icon: 'none' });
        }
      },
      fail: () => {
        this.setData({ isLoading: false });
        wx.showToast({ title: '网络错误，用户加载失败', icon: 'none' });
      }
    });
  },

  /**
   * 通过roleCode获取roleName
   */
  getRoleNameByCode(roleCode) {
    const { roles } = this.data;
    const matchedRole = roles.find(role => role.roleCode === roleCode);
    return matchedRole ? matchedRole.roleName : roleCode;
  },

  /**
   * 时间格式化
   */
  formatTime(timeStr) {
    return timeStr ? timeStr.split(' ').join(' ') : '';
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({ url: '/pages/login/login' });
    }
  },

  /**
   * 搜索用户
   */
  searchUsers() {
    this.setData({ currentPage: 1 }, () => {
      this.loadUsers();
    });
  },

  /**
   * 搜索输入变化
   */
  onSearchInput(e) {
    this.setData({ searchKey: e.detail.value });
  },

  /**
   * 上一页
   */
  prevPage() {
    if (this.data.currentPage > 1) {
      this.setData({ currentPage: this.data.currentPage - 1 }, () => {
        this.loadUsers();
      });
    }
  },

  /**
   * 下一页
   */
  nextPage() {
    if (this.data.currentPage < this.data.totalPages) {
      this.setData({ currentPage: this.data.currentPage + 1 }, () => {
        this.loadUsers();
      });
    }
  },

  /**
   * 显示添加用户弹窗
   */
  showAddUserModal() {
    const { roles } = this.data;
    this.setData({
      showUserModal: true,
      isEditMode: false,
      selectedRoleIndex: 0, // 默认选中第一个角色
      formData: {
        id: '',
        username: '',
        phone: '',
        avatarUrl: '',
        role: roles.length > 0 ? roles[0].roleCode : '',
        password: ''
      }
    });
  },

  /**
   * 显示编辑用户弹窗（计算角色索引）
   */
  showEditUserModal(e) {
    const user = e.currentTarget.dataset.user;
    const { roles } = this.data;
    
    // 计算当前用户角色在角色列表中的索引（修复关键）
    let selectedRoleIndex = 0;
    if (user.role) {
      const index = roles.findIndex(role => role.roleCode === user.role);
      selectedRoleIndex = index > -1 ? index : 0;
    }

    this.setData({
      showUserModal: true,
      isEditMode: true,
      selectedRoleIndex, // 设置选中索引
      formData: {
        id: user.id,
        username: user.username,
        phone: user.phone || '',
        avatarUrl: user.avatarUrl || '',
        role: user.role || '',
        password: ''
      }
    });
  },

  /**
   * 隐藏弹窗
   */
  hideUserModal() {
    this.setData({ showUserModal: false });
  },

  /**
   * 表单输入变化
   */
  onFormInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`formData.${field}`]: e.detail.value });
  },

  /**
   * 角色选择变化（更新索引和角色编码）
   */
  changeRole(e) {
    const { roles } = this.data;
    const selectedIndex = e.detail.value; // 选中的索引
    const selectedRoleCode = roles[selectedIndex].roleCode;
    
    this.setData({ 
      selectedRoleIndex: selectedIndex, // 更新索引
      [`formData.role`]: selectedRoleCode 
    });
  },

  /**
   * 提交表单
   */
  submitUserForm() {
    const { isEditMode, formData } = this.data;
    if (!formData.username.trim()) {
      wx.showToast({ title: '请输入用户名', icon: 'none' });
      return;
    }
    if (!isEditMode && !formData.password.trim()) {
      wx.showToast({ title: '请输入密码', icon: 'none' });
      return;
    }
    if (!formData.role) {
      wx.showToast({ title: '请选择角色', icon: 'none' });
      return;
    }

    isEditMode ? this.updateUser() : this.createUser();
  },

  /**
   * 新增用户
   */
  createUser() {
    const token = wx.getStorageSync('token');
    const { formData } = this.data;

    wx.request({
      url: app.globalData.baseUrl + '/api/users',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        username: formData.username.trim(),
        password: formData.password.trim(),
        phone: formData.phone.trim() || null,
        avatarUrl: formData.avatarUrl.trim() || null,
        role: formData.role
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '新增用户成功' });
          this.hideUserModal();
          this.loadUsers();
        } else {
          wx.showToast({ title: res.data.msg || '新增失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误，新增失败', icon: 'none' });
      }
    });
  },

  /**
   * 编辑用户
   */
  updateUser() {
    const token = wx.getStorageSync('token');
    const { formData } = this.data;

    const requestData = {
      username: formData.username.trim(),
      phone: formData.phone.trim() || null,
      avatarUrl: formData.avatarUrl.trim() || null,
      role: formData.role
    };
    if (formData.password.trim()) {
      requestData.password = formData.password.trim();
    }

    wx.request({
      url: `${app.globalData.baseUrl}/api/users/${formData.id}`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: requestData,
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '编辑成功' });
          this.hideUserModal();
          this.loadUsers();
        } else {
          wx.showToast({ title: res.data.msg || '编辑失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误，编辑失败', icon: 'none' });
      }
    });
  },

  /**
   * 确认删除用户
   */
  confirmDeleteUser(e) {
    const userId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认删除',
      content: '删除后不可恢复，是否继续？',
      success: (res) => {
        if (res.confirm) {
          this.deleteUser(userId);
        }
      }
    });
  },

  /**
   * 删除用户
   */
  deleteUser(userId) {
    const token = wx.getStorageSync('token');
    wx.request({
      url: `${app.globalData.baseUrl}/api/users/${userId}`,
      method: 'DELETE',
      header: { 'Authorization': `Bearer ${token}` },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '删除成功' });
          this.loadUsers();
        } else {
          wx.showToast({ title: res.data.msg || '删除失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误，删除失败', icon: 'none' });
      }
    });
  },

  /**
   * 阻止冒泡
   */
  stopPropagation() {}
});
